<template>
  <view>
    <view class="goods-list">
      <view v-for="(goods, i) in goodsList" :key="i" @click="gotoDetail(goods)">
        <my-goodslist :goods="goods"></my-goodslist>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        //请求参数对象
        queryObj: {
          //查询关键字
          query: '',
          //商品Id
          cid: '',
          //页码值
          pagenum: 1,
          // 每页显示多少条数据
          pagesize: 10
        },
        // 商品列表的数据
        goodsList: [],
        total: 0,
        //节流阀
        isolades: false,
      };
    },
    onLoad(options) {
      // 将页面参数转存到 this.queryObj 对象中
      this.queryObj.query = options.query || ''
      this.queryObj.cid = options.cid || ''
      this.getGoodsList()
      //console.log(options)
    },
    methods: {
      //获取商品列表
      async getGoodsList(cb) {
        this.isolades = true
        const {
          data: res
        } = await uni.$http.get("https://api-ugo-web.itheima.net/api/public/v1/goods/search", this.queryObj)
        //如果回调函数存在就执行
        cb && cb()
        if (res.meta.status !== 200) return uni.$showMsg()
        // 为数据赋值：通过展开运算符的形式，进行新旧数据的拼接
        this.goodsList = [...this.goodsList, ...res.message.goods]
        this.total = res.message.total
        this.isolades = false
      },
      //上拉触底加载函数
      onReachBottom() {
        // 判断是否还有下一页数据
        if (this.queryObj.pagenum * this.queryObj.pagesize > this.total) return uni.$showMsg('数据加载完毕')
        if (this.isolades) return
        this.queryObj.pagenum += 1
        // 重新获取列表数据
        this.getGoodsList()
      },
      //下拉刷新处理函数
      onPullDownRefresh() {
        this.total = 0
        this.goodsList = []
        this.isolades = false
        this.queryObj.pagenum = 1

        //重新发送请求
        this.getGoodsList(() => uni.stopPullDownRefresh())
      },
      gotoDetail(goods) {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + goods.goods_id
        })
      }
    },
    //过滤器
    filters: {
      // 把数字处理为带两位小数点的数字
      tofixed(num) {
        return Number(num).toFixed(2)
      }
    }
  }
</script>

<style lang="scss">
  .goodslist-item {
    display: flex;
    padding: 6px 5px;
    border-bottom: 2px solid #efefef;

    .left-goodslist-img {
      display: block;
      width: 100px;
      height: 100px;
      margin-right: 5px;
    }

    .right-goodslist-box {
      display: flex;
      flex-direction: column;
      justify-content: center;
      justify-content: space-between;

      .right-goodslist-text {
        font-size: 16px;
        color: #C00000;
      }
    }
  }
</style>
